package webInterface;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import db_manager.Manager;

/**
 * this class handles the user pressing the dir or file button in the web interface
 */
public class ContentOfDir extends HttpServlet
{
	/*
	 * this function handles the user pressing the dir or file button in the web interface 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		// get the user name
		String userName = session.getAttribute("userName").toString();
		//the user pressed on directory button
		if (request.getParameter("act") != null)
		{
			session.setAttribute("dirName", request.getParameter("act"));
			PrintWriter out = response.getWriter();
			String dirName = request.getParameter("act");
			File sessionFile = new File("C:\\Program Files\\m&l_dropbox_server\\hibernate.cfg.xml");
			// Opening a new session factory - for connection with DB
			SessionFactory sessionFactory = new Configuration().configure(sessionFile).buildSessionFactory();
			Session sessionDB = sessionFactory.openSession();
			long dir_id = Manager.getInstance().findDirId(sessionDB, dirName, userName);
			sessionDB.flush();
			// get the dir's files
			ArrayList<String> files =  Manager.getInstance().findFilesInDir(userName,request.getParameter("act"));
			// creating a form with this dir's files and also a submit button the share the dir
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Servlet Content</title>");
			out.println("</head>");
			out.println("<body>");
			String temp = "Directory name: "+ dirName;
			out.println("<form action=\"webInterface.SharingDir\" method=\"POST\">"+temp+"<input type=\"submit\" value=\"Share Directory\">  </form>");
			out.println("<tr/>");
			out.println("<TABLE>");
			String s;
			// for each file
			for (int i = 0; i < files.size(); i++) 
			{
				s = files.get(i) + "--dir_id:" + dir_id;
				out.println("	<form action=\"webInterface.ContentOfDir\" method=\"POST\"> \n <TD> <input type=\"submit\" name=\"act2\" value="+s+"> </TD> \n </form> \n");
				out.println("<tr/>");
			}          
			out.println("</TABLE>");  
			out.close();
		}
		//the user pressed on file button
		else
		{
			BufferedInputStream buf=null;
			ServletOutputStream myOut=null;
			try
			{
				String fileName = "";
				long dir_id = 0;
				// getting the button name
				String button = request.getParameter("act2");
				int index = button.indexOf("--dir_id:");
				// the case that this button name is proper
				if(index != -1)
				{
					fileName = button.substring(0, index);
					dir_id =  Long.parseLong(button.substring(index+9));
				}
				// getting the file to download
				File myfile =  Manager.getInstance().getTheFile(fileName, dir_id);
				myOut = response.getOutputStream( );
				//set response headers
				response.setContentType("text/plain");

				response.addHeader(
						"Content-Disposition","attachment; filename="+fileName);

				response.setContentLength((int) myfile.length( ) );

				FileInputStream input = new FileInputStream(myfile);
				buf = new BufferedInputStream(input);
				int readBytes = 0;

				//read from the file; write to the ServletOutputStream
				while((readBytes = buf.read( )) != -1)
				{
					myOut.write(readBytes);
				}

			} 
			catch (IOException ioe)
			{
				throw new ServletException(ioe.getMessage());
			} 
			finally 
			{
				//close the input/output streams
				if (myOut != null)
					myOut.close( );
				if (buf != null)
					buf.close( );
			}
		}
	}
}
